package com.chinaunicom.gateway.domain;

import com.alibaba.fastjson.JSONObject;
import com.chinaunicom.api.dto.MemberDTO;
import com.chinaunicom.gateway.domain.gateway.IMemberGateway;
import com.chinaunicom.gateway.infrastructure.gateway.MemberGateway;
import com.chinaunicom.common.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author guomenghuai
 * @date 2024/1/8
 * @Description
 */
@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    /**
     * 需要排除拦截的路径
     */
    private static final String EXCLUDE_PATH = "/api/member/login";

    private PathMatcher matcher = new AntPathMatcher();

    @Resource
    private IMemberGateway memberGateway;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求
        ServerHttpRequest request = exchange.getRequest();
        // 获取响应
        ServerHttpResponse response = exchange.getResponse();
        // 添加全局过滤，进行token的验证，
        String uriPath = request.getURI().getPath();
        // /api/member/login
        log.info("req param[uriPath={}]", uriPath);
        // 用户微服务和验证码微服务的请求放行
        if (match(EXCLUDE_PATH, uriPath)) {
            return chain.filter(exchange);
        }

        List<String> tokens = request.getHeaders().get(Constants.AUTHORIZE_TOKEN);

        if (!CollectionUtils.isEmpty(tokens)) {
            String token = tokens.get(0);
            log.info("token:{}", token);
            // token为空 不放行
            if (StringUtils.isBlank(token)) {
                response.setStatusCode(HttpStatus.FORBIDDEN);
                return response.setComplete();
            }
            // 校验token,token不正确会返回null，token正确会返回用户邮箱
            MemberDTO memberDTO = memberGateway.info(token);
            log.info("会员信息:{}", JSONObject.toJSONString(memberDTO));
            if (Objects.isNull(memberDTO)) {
                response.setStatusCode(HttpStatus.FORBIDDEN);
                return response.setComplete();
            }
            return chain.filter(exchange);
        }
        // 没有token不放行
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    private boolean match(String excludePath, String urlPath){
        String[] excludePaths = excludePath.split(",");
        if (excludePaths != null && excludePaths.length > 0) {
            for (String path : excludePaths) {
                boolean match = matcher.match(path, urlPath);
                if (match) {
                    log.info("url 匹配上了");
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
